<?php

namespace Tbf\Bundle\CacheBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Tbf\Component\FileSystem\FileSystemFunction;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class TbfCacheExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
/*
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
*/
        switch($config['type']){
            case 'array':
                $def = $this->getArrayCacheDefinition($config);
                break;
            case 'static_array':
                $def = $this->getStaticArrayCacheDefinition($config);
                break;
            case 'memcache':
                $def = $this->getMemcacheCacheDefinition($config);
                break;
            case 'file_system':
                $def = $this->getFileSystemCacheDefinition($config);
        }
        $container->setDefinition('tbf_cache',$def);
        $this->addClassesToCompile(array(
            'Doctrine\Common\Cache\Cache',
            'Doctrine\Common\Cache\CacheProvider',
        ));
    }
    protected function getArrayCacheDefinition(array $config){
        return new Definition('Doctrine\Common\Cache\ArrayCache');
    }
    protected function getStaticArrayCacheDefinition(array $config){
        return new Definition('Tbf\Bundle\CacheBundle\Services\StaticArrayCache');
    }
    protected function getMemcacheCacheDefinition(array $config){
        $memcache_obj = new Definition('Memcache');
        if ($config['port']===null){
            $config['port'] = 11211;
        }
        $memcache_obj->addMethodCall('connect',array(
            $config['host'],$config['port']
        ));

        $memcache_cache = new Definition('Doctrine\Common\Cache\MemcacheCache');
        $memcache_cache->addMethodCall('setMemcache',array(
            $memcache_obj
        ));
        return $memcache_cache;
    }
    protected function getFileSystemCacheDefinition(array $config){
        if ($config['path']===null){
            $path = '%kernel.cache_dir%/tbf_cache';
        }else{
            $path = $config['path'];
        }
        $def = new Definition('Doctrine\Common\Cache\FilesystemCache');
        $def->addArgument($path);
        return $def;
    }
}
